package com.skymxc.wandroidtodo.data.net;

import androidx.annotation.NonNull;

import com.skymxc.wandroidtodo.data.pref.PrefUtils;
import com.skymxc.wandroidtodo.entity.NetResponseException;
import com.skymxc.wandroidtodo.mvp.IView;
import com.skymxc.wandroidtodo.page.base.BaseActivity;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;

/**
 * <p>
 *
 * </p>
 *
 * @author 孟祥超
 * <p>
 * date: 2021/12/2  7:33 上午
 */
public abstract class NetObserver<T> implements Observer<T> {
    private CompositeDisposable compositeDisposable;
    private IView view;

    public NetObserver(CompositeDisposable compositeDisposable, IView view) {
        this.compositeDisposable = compositeDisposable;
        this.view = view;
    }

    @Override
    public void onSubscribe(@NonNull Disposable d) {
        //防止内存泄漏
        compositeDisposable.add(d);
    }

    @Override
    public void onError(@NonNull Throwable e) {
        e.printStackTrace();
        if (e instanceof NetResponseException) {
            NetResponseException netResponseException = (NetResponseException) e;
            if (netResponseException.getErrorCode() == -1001) {
                //对登陆超时做个处理
                if (view instanceof BaseActivity) {
                    PrefUtils.removeUser();
                    BaseActivity activity = (BaseActivity) view;
                    activity.toLogin();
                }else{
                    view.showError(((NetResponseException) e).getErrorMsg(), ((NetResponseException) e).getErrorCode());
                }
            } else {
                view.showError(((NetResponseException) e).getErrorMsg(), ((NetResponseException) e).getErrorCode());
            }
        } else {
            //错误处理
            view.showError(e.getMessage(), -1);
        }
    }

    @Override
    public void onComplete() {

    }
}
